package org.zebra.web.filter;

import org.springframework.util.PathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;
import org.zebra.common.util.UriWhiteUtil;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Set;

/**
 * xss filter
 *
 * @author zhanghongbin
 */
public class XssFilter extends OncePerRequestFilter {

    private Set<String> excludeUrls;
    /**
     * 路径匹配器
     */
    private PathMatcher pathMatcher;

    public XssFilter(Set<String> excludeUrls, PathMatcher pathMatcher) {
        this.excludeUrls = excludeUrls;
        this.pathMatcher = pathMatcher;
        this.excludeUrls.addAll(UriWhiteUtil.getDefaultUriWhite());
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws IOException, ServletException {
        filterChain.doFilter(new XssRequestWrapper(request), response);
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) {
        // 如果匹配到无需过滤，则不过滤
        String uri = request.getServletPath();
        return excludeUrls.stream().anyMatch(excludeUrl -> pathMatcher.matchStart(excludeUrl, uri));
    }
}
